package cn.bone.mqtt.demo02;

import cn.bone.mqtt.demo01.PushCallback;
import com.alibaba.fastjson.JSON;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by MD-01 on 2017/4/21.
 */
public class Client {

    private static Logger logger = LoggerFactory.getLogger(Client.class);

    public static void main(String[] args) throws MqttException {

        String host = "tcp://127.0.0.1:1883";
       //String host = "tcp://127.0.0.1:61613";
        String topic = "demo02/client";

        for(int i=1;i<=2;i++){
            MqttClient client = new MqttClient(host,"clientId-"+i,new MemoryPersistence());
            MqttConnectOptions options = new MqttConnectOptions();
            options.setCleanSession(false);
            options.setUserName("admin");
            options.setPassword("password".toCharArray());
            client.connect(options);
            client.subscribe("server02Will",2,new IMqttMessageListener() {
                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    logger.info("收到<"+topic+">的消息:("+message.getId()+")"+ new String(message.getPayload(),"UTF-8"));
                    client.messageArrivedComplete(message.getId(),message.getId());
                }
            });

            client.subscribe(topic, 2, new IMqttMessageListener() {
                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    logger.info("收到<"+topic+">的消息:("+message.getId()+")"+ new String(message.getPayload(),"UTF-8"));
                    client.messageArrivedComplete(message.getId(),message.getId());
                }
            });
        }
    }
}
